package tron.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.context.annotation.Conditional;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description  消息监听根据条件加载，可根据配置文件切换消息服务器
 * @auther tron
 * @create 2019-11-08
 */
@Service
@Conditional(RabbitCondition.class)
@Slf4j
public class TronAmqpMessageReceive {


    /**
     * 消息确认机制
     * @param message
     * @param channel
     * @param tag
     */
    @RabbitListener(queues = "queue",ackMode = "MANUAL")
    public void process(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        log.info("======收到queue消息：======{}",message);
        log.info("===消息id:{}===",tag);

        // 调用方法保存消息时，遇到数据库错误这类的问题,需要把消息放回队列，之后消费。
        // 这种方式会导致循环，应该有延迟的处理
        if (true) {
            try {
                Thread.sleep(5000);
                channel.basicReject(tag,true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            // 手动确认消息
        channel.basicAck(tag,false);
        }
    }

    //订阅模式

    @RabbitListener(queues="queue1")    //监听器监听指定的Queue
    public void process1(String string) {
        log.info("======topic01收到topic消息：======{}",string);
    }


//    @RabbitListener(queues="queue2")    //监听器监听指定的Queue
//    public void process2(String string) {
//        log.info("======topic02收到topic消息：======{}",string);
//    }

    @RabbitListener(queues="queue3")    //监听器监听指定的Queue
    public void process3(String string) {
        log.info("======topic03收到topic消息：======{}",string);
    }



    //广播模式

    @RabbitListener(queues="fanout.A")
    public void processA(String string) {
        log.info("======收到fanout消息：======{}",string);
    }

    @RabbitListener(queues="fanout.B")
    public void processB(String string) {
        log.info("======收到fanout消息：======{}",string);
    }

    @RabbitListener(queues="fanout.C")
    public void processC(String string) {
        log.info("======收到fanout消息：======{}",string);
    }


}
